<template>
  <n-config-provider :theme="theme" :theme-overrides="themeOverrides">
    <div class="register-container">
      <div class="theme-switch" @click="toggleTheme">
        <n-icon size="22">
          <SunnyOutline v-if="theme === null" />
          <MoonOutline v-else />
        </n-icon>
      </div>

      <div class="register-box">
        <div class="register-left">
          <div class="welcome-text">
            <h1>欢迎加入</h1>
            <p>请填写您的注册信息</p>
          </div>
        </div>

        <n-card class="register-right" :bordered="false">
          <div class="register-header">
            <h2>用户注册</h2>
            <p class="subtitle">创建您的账号</p>
          </div>

          <n-form
            ref="formRef"
            :model="formValue"
            :rules="rules"
            label-placement="left"
            label-width="0"
            size="large"
          >
            <n-form-item path="username">
              <n-input
                v-model:value="formValue.username"
                placeholder="请输入用户名"
                clearable
              >
                <template #prefix>
                  <n-icon
                    :component="PersonOutline"
                    :color="theme === null ? '#64748B' : '#94A3B8'"
                  />
                </template>
              </n-input>
            </n-form-item>

            <n-form-item path="password">
              <n-input
                v-model:value="formValue.password"
                type="password"
                show-password-on="click"
                placeholder="请输入密码"
              >
                <template #prefix>
                  <n-icon
                    :component="LockClosedOutline"
                    :color="theme === null ? '#64748B' : '#94A3B8'"
                  />
                </template>
              </n-input>
            </n-form-item>

            <n-form-item path="confirmPassword">
              <n-input
                v-model:value="formValue.confirmPassword"
                type="password"
                show-password-on="click"
                placeholder="请确认密码"
              >
                <template #prefix>
                  <n-icon
                    :component="LockClosedOutline"
                    :color="theme === null ? '#64748B' : '#94A3B8'"
                  />
                </template>
              </n-input>
            </n-form-item>

            <n-form-item path="realName">
              <n-input
                v-model:value="formValue.realName"
                placeholder="请输入真实姓名"
                clearable
              >
                <template #prefix>
                  <n-icon
                    :component="PersonCircleOutline"
                    :color="theme === null ? '#64748B' : '#94A3B8'"
                  />
                </template>
              </n-input>
            </n-form-item>

            <n-form-item path="email">
              <n-input
                v-model:value="formValue.email"
                placeholder="请输入邮箱（可选）"
                clearable
              >
                <template #prefix>
                  <n-icon
                    :component="MailOutline"
                    :color="theme === null ? '#64748B' : '#94A3B8'"
                  />
                </template>
              </n-input>
            </n-form-item>

            <n-form-item path="phone">
              <n-input
                v-model:value="formValue.phone"
                placeholder="请输入手机号（可选）"
                clearable
              >
                <template #prefix>
                  <n-icon
                    :component="PhonePortraitOutline"
                    :color="theme === null ? '#64748B' : '#94A3B8'"
                  />
                </template>
              </n-input>
            </n-form-item>
          </n-form>

          <div style="margin-top: 24px">
            <n-button
              type="primary"
              size="large"
              block
              :loading="loading"
              @click="handleRegister"
              class="submit-btn"
            >
              立即注册
            </n-button>
          </div>

          <div class="tips" style="margin-top: 16px; text-align: center;">
            <n-button text @click="router.push('/login')">
              已有账号？立即登录
            </n-button>
          </div>

          <div class="register-footer">
            <n-text depth="3">
              Copyright © {{ new Date().getFullYear() }}
            </n-text>
          </div>
        </n-card>
      </div>
    </div>
  </n-config-provider>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useMessage } from 'naive-ui'
import {
  PersonOutline,
  LockClosedOutline,
  PersonCircleOutline,
  MailOutline,
  PhonePortraitOutline,
  SunnyOutline,
  MoonOutline
} from '@vicons/ionicons5'
import { register } from '../../api/auth'
import { darkTheme } from 'naive-ui'
import { useThemeStore } from '@/stores/theme'

const router = useRouter()
const message = useMessage()
const formRef = ref(null)
const loading = ref(false)

const themeStore = useThemeStore()
const theme = computed(() => themeStore.theme)
const themeOverrides = computed(() => themeStore.themeOverrides)
const toggleTheme = () => themeStore.toggleTheme()

const formValue = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  realName: '',
  email: '',
  phone: ''
})

const validatePassword = (rule, value) => {
  if (!value) {
    return new Error('请输入密码')
  }
  if (value.length < 6) {
    return new Error('密码不能少于6个字符')
  }
  return true
}

const validateConfirmPassword = (rule, value) => {
  if (!value) {
    return new Error('请确认密码')
  }
  if (value !== formValue.password) {
    return new Error('两次输入密码不一致')
  }
  return true
}

const validateEmail = (rule, value) => {
  if (!value) {
    return true
  }
  if (!/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/.test(value)) {
    return new Error('请输入正确的邮箱地址')
  }
  return true
}

const validatePhone = (rule, value) => {
  if (!value) {
    return true
  }
  if (!/^1[3-9]\d{9}$/.test(value)) {
    return new Error('请输入正确的手机号')
  }
  return true
}

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, message: '用户名不能少于3个字符', trigger: 'blur' }
  ],
  password: [
    { validator: validatePassword, trigger: 'blur' }
  ],
  confirmPassword: [
    { validator: validateConfirmPassword, trigger: 'blur' }
  ],
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' }
  ],
  email: [
    { validator: validateEmail, trigger: 'blur' }
  ],
  phone: [
    { validator: validatePhone, trigger: 'blur' }
  ]
}

const handleRegister = () => {
  if (!formRef.value) return

  formRef.value.validate(async (errors) => {
    if (!errors) {
      loading.value = true
      try {
        const { username, password, realName, email, phone } = formValue
        const registerData = {
          username,
          password,
          realName
        }
        if (email?.trim()) {
          registerData.email = email.trim()
        }
        if (phone?.trim()) {
          registerData.phone = phone.trim()
        }
        await register(registerData)
        message.success('注册成功')
        router.push('/login')
      } catch (error) {
        console.error('注册失败:', error)
        message.error(error.message || '注册失败，请重试')
      } finally {
        loading.value = false
      }
    }
  })
}
</script>

<style scoped>
.register-container {
  width: 100vw;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: v-bind('theme === null ? "linear-gradient(135deg, #F0F9FF 0%, #E0F2FE 100%)" : "linear-gradient(135deg, #17171A 0%, #1C1C1C 100%)"');
  position: relative;
  overflow: hidden;
}

.register-box {
  display: flex;
  width: 900px;
  height: 720px;
  border-radius: 24px;
  overflow: hidden;
  box-shadow: 0 4px 24px rgba(0, 0, 0, 0.1);
}

.register-left {
  flex: 1;
  background: v-bind('theme === null ? "linear-gradient(135deg, #0EA5E9 0%, #0284C7 100%)" : "linear-gradient(135deg, #101010 0%, #1A1A1A 100%)"');
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px;
  position: relative;
  overflow: hidden;
}

.welcome-text {
  color: #ffffff;
  text-align: center;
  position: relative;
  z-index: 1;
}

.welcome-text h1 {
  font-size: 36px;
  margin-bottom: 16px;
  font-weight: 600;
  letter-spacing: 1px;
}

.welcome-text p {
  font-size: 18px;
  opacity: 0.9;
  letter-spacing: 0.5px;
}

.register-right {
  flex: 1;
  padding: 20px 40px;
  display: flex;
  flex-direction: column;
  position: relative;
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
}

.register-header {
  text-align: center;
  margin-bottom: 12px;
}

.register-header h2 {
  font-size: 22px;
  margin-bottom: 2px;
  font-weight: 600;
  color: v-bind('theme === null ? "#0369A1" : "#C2C7D0"');
  letter-spacing: 0.5px;
}

.subtitle {
  font-size: 13px;
  letter-spacing: 0;
}

:deep(.n-form-item) {
  margin-bottom: 8px;
}

:deep(.n-form-item-feedback-wrapper) {
  min-height: 18px;
}

:deep(.n-input) {
  height: 34px;
  line-height: 34px;
}

:deep(.n-input__input-el) {
  height: 34px;
  line-height: 34px;
  padding-top: 0;
  padding-bottom: 0;
}

:deep(.n-input__prefix) {
  height: 34px;
  margin-right: 8px;
  display: flex;
  align-items: center;
}

:deep(.n-input-wrapper) {
  padding-top: 0;
  padding-bottom: 0;
}

.tips {
  margin-top: 4px !important;
  text-align: center;
}

.register-footer {
  margin-top: 8px;
  padding: 8px 0;
  text-align: center;
}

.theme-switch {
  position: absolute;
  top: 20px;
  right: 20px;
  cursor: pointer;
  background: v-bind('theme === null ? "rgba(255, 255, 255, 0.9)" : "rgba(255, 255, 255, 0.15)"');
  border-radius: 50%;
  padding: 10px;
  backdrop-filter: blur(8px);
  transition: all 0.3s ease;
  color: v-bind('theme === null ? "#0369A1" : "#FFFFFF"');
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  z-index: 100;
}

.theme-switch:hover {
  background: v-bind('theme === null ? "#FFFFFF" : "rgba(255, 255, 255, 0.25)"');
  color: v-bind('theme === null ? "#0EA5E9" : "#FFFFFF"');
  transform: rotate(30deg);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}
</style>
